package com.xunyin.modules.qrcode.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xunyin.common.service.impl.BaseServiceImpl;
import com.xunyin.enums.WxQrcodeTypeEnum;
import com.xunyin.modules.qrcode.domain.QrcodeDO;
import com.xunyin.modules.qrcode.service.QrcodeService;
import com.xunyin.modules.qrcode.service.mapper.QrcodeMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.Date;
import java.util.SortedMap;
import java.util.TreeMap;

import static com.xunyin.exception.ServiceExceptionUtil.exception;
import static com.xunyin.exception.enums.ErrorCodeConstants.CREATE_QRCODE_FAIL;


/**
 * 二维码 Service 实现类
 *
 * @author yshop
 */
@Service
@Slf4j
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class QrcodeServiceImpl extends BaseServiceImpl<QrcodeMapper, QrcodeDO> implements QrcodeService {

    //@Resource
    @Autowired
    private QrcodeMapper qrcodeMapper;


    @Value("${file.path}")
    private String filePath;

    /**
     * 创建小程序二维码
     * @param page 跳转的页面
     * @param scene 参数
     * @param isUpdate 是否覆盖
     * @param env  小程序发布环境 MiniQrcodeEnvEnum
     * @return
     */
    @Override
    public QrcodeDO createMiniQrcode(String page, String scene, Boolean isUpdate, String env,WxMaService wxMaService) {

        log.info("wxMaService.getWxMaConfig().getAppid():"+wxMaService.getWxMaConfig().getAppid());
        String hashStr = DigestUtil.md5Hex(wxMaService.getWxMaConfig().getAppid()+page+scene+env);
        QrcodeDO qrcodeDO = qrcodeMapper.selectOne(new LambdaQueryWrapper<QrcodeDO>().eq(QrcodeDO::getHash,hashStr));
        if(qrcodeDO == null || isUpdate) {
            try {
                String path = filePath + "qrcode" + File.separator;
                //String path = "";
                //String path1 = path + "qrcode" + File.separator;
                FileUtil.mkdir(new File(path));
                //WxMaService wxMaService = WxMaConfiguration.getWxMaService();
                //File file = wxMaService.getQrcodeService().createWxaCodeUnlimit(scene,page,path,false,env,600, true,null, false);
                File file = wxMaService.getQrcodeService().createWxaCodeUnlimit(scene,page,path,600,true,null,false);
                //File createWxaCodeUnlimit(String var1, String var2, String var3, int var4, boolean var5, WxMaCodeLineColor var6, boolean var7) throws WxErrorException;
                //File file = null;
                String fileName = IdUtil.randomUUID() + ".jpg";
                File target = new File(path + fileName);
                //临时文件移动到磁盘
                FileUtil.copyFile(file,target);
                QrcodeDO qrcodeDO1 = new QrcodeDO();
                qrcodeDO1.setType(WxQrcodeTypeEnum.MINI_UNLIMIT.getValue());
                qrcodeDO1.setHash(hashStr);
                SortedMap<Object, Object> sortedMap = new TreeMap<Object, Object>() {
                    private static final long serialVersionUID = 1L;
                    {
                        put("page", page);
                        put("scene", scene);
                        put("env", env);
                    }};
                qrcodeDO1.setData(JSONUtil.toJsonStr(sortedMap));
                qrcodeDO1.setSrc("file" + File.separator  +"qrcode" + File.separator + fileName);
                qrcodeDO1.setFullPath(path + fileName);
                qrcodeDO1.setCreateTime(new Date());
                qrcodeMapper.insert(qrcodeDO1);

                return qrcodeDO1;
            } catch (Exception e) {
                log.error(e.getMessage());
                throw exception(CREATE_QRCODE_FAIL);
            }
        }

        return qrcodeDO;
    }

    /**
     * 创建普通二维码
     * @param page 跳转的页面
     * @param scene 参数
     * @param isUpdate 是否覆盖
     * @return
     */
    @Override
    public QrcodeDO createQrcode(String page, String scene, Boolean isUpdate) {
        return  null;
/*        String hashStr = DigestUtil.md5Hex(H5Url + page + scene);
        QrcodeDO qrcodeDO = qrcodeMapper.selectOne(new LambdaQueryWrapper<QrcodeDO>().eq(QrcodeDO::getHash,hashStr));
        String url = H5Url +"/#/" + page + "?scene=" + UriUtils.encode(scene,"UTF-8");

        System.out.println("url:"+url);


        if(qrcodeDO == null || isUpdate) {
            String path = filePath + "qrcode" + File.separator;
            String fileName = IdUtil.randomUUID() + ".jpg";;
            File target = new File(path + fileName);
            QrCodeUtil.generate(url, 680, 680, target);
            QrcodeDO qrcodeDO2 = new QrcodeDO();
            qrcodeDO2.setType(WxQrcodeTypeEnum.NORMAL.getValue());
            qrcodeDO2.setHash(hashStr);
            SortedMap<Object, Object> sortedMap = new TreeMap<Object, Object>() {
                private static final long serialVersionUID = 1L;
                {
                    put("page", url);
                    put("scene", scene);
                }};
            qrcodeDO2.setData(JSONUtil.toJsonStr(sortedMap));
            qrcodeDO2.setSrc("file" + File.separator  +"qrcode" + File.separator + fileName);
            qrcodeDO2.setFullPath(path + fileName);
            qrcodeMapper.insert(qrcodeDO2);

            return qrcodeDO2;
        }

        return qrcodeDO;*/
    }



}
